package com.ls.lspicturebackend.manger;

import cn.hutool.core.io.FileUtil;
import com.ls.lspicturebackend.config.CosClientConfig;
import com.ls.lspicturebackend.exception.BusinessException;
import com.ls.lspicturebackend.exception.ErrorCode;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.GetObjectRequest;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.PicOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

@Component
public class CosManager {

    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private COSClient cosClient;

    /**
     * 上传对象
     *
     * @param key  唯一键
     * @param file 文件
     */
    public PutObjectResult putObject(String key, File file) {
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosClientConfig.getBucket(), key,
                file);
        return cosClient.putObject(putObjectRequest);
    }

    /**
     * 下载对象
     *
     * @param key 唯一键
     */
    public COSObject getObject(String key) {
        GetObjectRequest getObjectRequest = new GetObjectRequest(cosClientConfig.getBucket(), key);
        return cosClient.getObject(getObjectRequest);
    }

    /**
     * 上传图片对象
     *
     * @param key  唯一键
     * @param file 文件
     */
    public PutObjectResult putPictureObject(String key, File file) {
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosClientConfig.getBucket(), key,
                file);
        // 对图像进行处理 https://cloud.tencent.com/document/product/436/55377
        PicOperations picOperations = new PicOperations();
        // 原图返回
        picOperations.setIsPicInfo(1);
        // 将原图转化为WebP格式
        String webKey = FileUtil.mainName(key) + ".WebP";
        List<PicOperations.Rule> rules = new LinkedList<>();
        PicOperations.Rule rule = new PicOperations.Rule();
        rule.setBucket(cosClientConfig.getBucket());
        rule.setFileId(webKey);
        rule.setRule("imageMogr2/format/webp");
        rules.add(rule);
        // 只有当图片大小大于200kb才生成缩略图
        if (file.length() > 200 * 1024) {
            PicOperations.Rule thumbnailRule = new PicOperations.Rule();
            thumbnailRule.setBucket(cosClientConfig.getBucket());
            String thumbnailKey = FileUtil.mainName(key) + "_thumbnailKey." + FileUtil.getSuffix(key);
            thumbnailRule.setFileId(thumbnailKey);
            thumbnailRule.setRule(String.format("imageMogr2/thumbnail/%sx%s>", 256, 256));
            rules.add(thumbnailRule);
        }
        picOperations.setRules(rules);
        putObjectRequest.setPicOperations(picOperations);
        return cosClient.putObject(putObjectRequest);
    }

    public boolean checkPictureObjectExist(String key) {
        return cosClient.doesObjectExist(cosClientConfig.getBucket(), key);
    }

    public String processImageUrl(String originalImageUrl) {
        final List<String> ALLOW_PICTURE_SUFFIX = Arrays.asList("jpeg", "png", "jpg");
        String originalImageSuffix = FileUtil.getSuffix(originalImageUrl);
        if (ALLOW_PICTURE_SUFFIX.contains(originalImageSuffix)) {
            return originalImageUrl;
        }
        final String WEBP_SUFFIX = "WebP";
        String prefix = originalImageUrl.substring(0, 60);
        String key = originalImageUrl.substring(60);
        if (!WEBP_SUFFIX.equals(FileUtil.getSuffix(key))) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "图片格式错误，无法搜索");
        }
        key = key.substring(0, key.length() - WEBP_SUFFIX.length());
        for (String suffix : ALLOW_PICTURE_SUFFIX) {
            String newKey = key + suffix;
            if (checkPictureObjectExist(newKey)) {
                return prefix + newKey;
            }
        }
        throw new BusinessException(ErrorCode.PARAMS_ERROR, "图片不存在，无法搜索");
    }

}
